﻿using SimpleTerminal.Common;
using SimpleTerminal.Http;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace SimpleTerminal
{
    public partial class UpgradeForm : Form
    {
        string upgradeDownloadUrl = "";
        string upgradePageUrl = "";
        public UpgradeForm()
        {
            InitializeComponent();
            //this.btnCheckUpdate.FlatAppearance.BorderSize = 1;
            flatButton2.Enabled = false;
        }

        private void BtnCheckUpdate_Click(object sender, EventArgs e)
        {
            CheckUpdate();
        }

        private void CheckUpdate()
        {
            flatButton1.Text = "检测更新中...";
            string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            Api.DoRequest("http://xueshengji.dingd.cn/upgrade.php?version=" + version, new Api.RequesetCallback(RequestCallback));
        }

        private void RequestCallback(Response response)
        {
            BeginInvoke((EventHandler)delegate
            {
                flatButton1.Text = "检测更新";
                if (response.Code != 0)
                {
                    Log.Debug("UpgradeForm", "通讯失败" + response.Code + " msg:" + response.Msg);
                    return;
                }
                if ("need".Equals(response.Data.Upgrade))
                {
                    richTextBox1.Text = "检测到新版本\r\n";
                    richTextBox1.Text += response.Data.Describe;
                    Log.Debug("UpgradeForm", "需要更新 地址:" + response.Data.UpgradeUrl);
                    upgradePageUrl = response.Data.UpgradeUrl;
                    flatButton2.Enabled = true;
                }
                else
                {
                    richTextBox1.Text = "没有检测到新版本";
                    flatButton2.Enabled = false;
                }
            });


        }

        private void Panel1_Paint(object sender, PaintEventArgs e)
        {
        }

        private void UpgradeForm_Paint(object sender, PaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(richTextBox1.Location.X - 1,
                richTextBox1.Location.Y - 1,
                richTextBox1.Width + 1,
                richTextBox1.Height + 1);

            e.Graphics.DrawRectangle(new Pen(SystemColors.GrayText, 1), rectangle);
        }

        private void UpgradeForm_Load(object sender, EventArgs e)
        {
            CheckUpdate();
        }

        private void FlatButton2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(upgradePageUrl);
        }

        private void FlatButton1_Click(object sender, EventArgs e)
        {
            CheckUpdate();
        }
    }
}
